﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Garden;
using Garden.Func;
using Garden.Model;
using Kaixin.BLL;
using System.Text.RegularExpressions;
using System.Collections;
using System.Threading;
using System.Net;
using Kaixin.BLL.Func;
using Kaixin.BLL.Helper;
using System.IO;
using Kaixin.BLL.Model;

namespace Kaixin
{
    public delegate void ConsoleWrite(string msg);
    public delegate void MyDelegate();
    public partial class MainForm : Form
    {
        private UserID bll_userID = new UserID();
        private Firends bll_firend = new Firends();
        private string _myUID = string.Empty;
        private List<Thread> _pool = new List<Thread>();

        public MainForm()
        {
            InitializeComponent();
            
        }
        private void WriteLog(string msg)
        {
            if (rtbConsole.InvokeRequired)
            {
                this.Invoke(new ConsoleWrite(WriteLog), msg);
            }
            else
            {
                rtbConsole.Text += msg + Environment.NewLine;
                rtbConsole.SelectionStart = rtbConsole.Text.Length;
                rtbConsole.SelectionLength = 0;
                rtbConsole.ScrollToCaret();
            }
            
        }
        private bool ValidateUser()
        {
            return _myUID != string.Empty;
        }
        //private void BindMyFirendsGrid()
        //{
        //    bll_firend.MyFirends = bll_userID.GetFriendsList();
        //    GridView.DataSource = bll_firend.MyFirends;
        //    CheckALL();
        //    WriteLog(string.Format("我的好友（{0}）", bll_firend.MyFirends.Count));
        //    tabMyFriend.Text = string.Format("我的好友（{0}）", bll_firend.MyFirends.Count);
        //}
        #region  Thread        

        private void Login(Object x)
        {
            Login form = (Login)x;
            try
            {
               _myUID = bll_userID.GetUid(form.Email, form.PWD);
               WriteLog(string.Format("用户登录{0}", ValidateUser()?"成功":"失败"));
                //WriteLog("加载好友信息中...");
                //this.Invoke(new MyDelegate(BindMyFirendsGrid));
            }
            catch (WebException)
            {
                WriteLog("用户登录失败！请重新登录");
            }            
            
        }
        //2已经是好友，3需通过验证，4ok，5你的好友数已超过1000，6问题，7只有她好友的好友才可以给她发送好友请求，8对方已经到上限
        private void AddFirends()
        {
            //bll_firend.FirendsFirend
            List<DictionaryEntry> list = new List<DictionaryEntry>();
          //  list.Add(new DictionaryEntry(){ Key="11837071",Value="鸣鸣"});
            list.Add(new DictionaryEntry() { Key = "1961883", Value = "周白" });
            //list.Add(new DictionaryEntry() { Key = "11833611", Value = "吴小震" });
            //list.Add(new DictionaryEntry() { Key = "11838209", Value = "吴震震" });
            //list.Add(new DictionaryEntry() { Key = "11835338", Value = "吴小鸣" });
            //foreach (var item in list)
            //{
            //    Thread.Sleep(10000);
            //    switch (bll_firend.AddFriend(item))
            //    {
            //        case "2": WriteLog(string.Format("{0}已经是你的好友", item.Value)); break;
            //        case "3": WriteLog(string.Format("{0}需通过验证", item.Value)); break;
            //        case "4": WriteLog(string.Format("{0}请求已发出", item.Value)); break;
            //        case "5": WriteLog("你的好友数已超过1000无法再加好友"); break;
            //        case "6": WriteLog(string.Format("{0}有提问验证", item.Value)); break;
            //        case "7": WriteLog(string.Format("只有{0}好友的好友才可以给她发送好友请求", item.Value)); break;
            //        case "8": WriteLog(string.Format("{0}已经到上限", item.Value)); break;
            //        default: WriteLog(string.Format("{0}意外类型", item.Value)); break;
            //    }
            //}
            string url = "http://www.kaixin001.com/friend/addverify.php";
            string postData = "from=&content=hi&rcode=&code=&touid=";
            Random rand = new Random();
            string html = WebHelper.Post(url, postData + "1961883", "http://www.kaixin001.com/friend/new.php?touid=1961883");
            FileInfo f = new System.IO.FileInfo("xx.html");
            StreamWriter sw = new StreamWriter(f.Create());
            sw.Write(html);
            sw.Close();
                List<GroupCollection> gc = RegexHelper.Matches(html, RegexHelper.AddFirendReturnType);

                string t = gc.Count == 0 ? "访问过快" : RegexHelper.Matches(html, RegexHelper.AddFirendReturnType)[0][1].Value;
                WriteLog(t);
            
        }

        private void UpdateFirendInfo()
        {
            Config config = Config.CreateConfig();
            WriteLog("开始更新好友信息...");
            config.FirendList = bll_userID.GetFriendsList();
            WriteLog(string.Format("好友信息更新完毕共{0}好友", config.FirendList.Count));

        }
        #endregion
        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }
       
        private void 用户登陆ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Login login = new Login(bll_userID);
            login.ShowDialog();
            tabControl1.SelectedTab = tabConsole;
            rtbConsole.Text = string.Empty;
            WriteLog("用户登录中...");
            Thread t = new Thread(Login);
            t.Name = "loginThread";
            t.Start(login);
        }
      
        //返回被选中好友的UID
        //private List<DictionaryEntry> GetCheckedUid()
        //{
        //    List<DictionaryEntry> list = new List<DictionaryEntry>();
            
        //    foreach (DataGridViewRow row in GridView.Rows)
        //    {
        //        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["cbxFirend"];

        //        if (cell.Value !=null && (bool)cell.Value)
        //        {
        //            list.Add((DictionaryEntry)row.DataBoundItem);
        //        }
        //    }
        //    return list;
        //}
       

        private void 添加好友的好友为好友ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Thread t = new Thread(AddFirends);
            //t.Start();
            MessageBox.Show("该功能被屏蔽", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void StatisticsFirendsInfo(object arg)
        {
            List<User> result = new List<User>();
            List<User> list = (List<User>)arg;
            foreach (var item in list)
            {
                List<User> firends = bll_userID.GetFriendsList(item.UID);
                WriteLog(string.Format("好友{0}共有{1}好友", item.Name, firends.Count));
                result.AddRange(firends);
            }
            bll_firend.FirendsFirend = result.Distinct().ToList();
            WriteLog(string.Format("好友信息搜索结束,可加为好友的共有{0}位", bll_firend.FirendsFirend.Count));
        }

        private void 统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //tabControl1.SelectedTab = tabConsole;
            //WriteLog("开始好友信息搜索...");
            //List<DictionaryEntry> list = GetCheckedUid();
            //Thread t = new Thread(StatisticsFirendsInfo);
            //t.Start(list);
            MessageBox.Show("该功能被屏蔽", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        private void 更新好友信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ValidateUser())
            {
                Thread t = new Thread(UpdateFirendInfo);
                t.Name = "updateThread";
                _pool.Add(t);
                t.Start();
            }
            else
            {
                MessageBox.Show("请先登陆");
            }
            
        }


        #region debug
        private void 代码测试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Farmer f = new Farmer(new LogWrite(WriteLog), bll_userID.MyUID);
            //Thread t = new Thread(f.DoWork);
            //t.Start();        
            List<Seed> list = new List<Seed>();
            list.Add(new Seed { ID = "1", name = "1" });
            list.Add(new Seed { ID = "2", name = "2" });
            list.Add(new Seed { ID = "3", name = "3" });
            Seed seed = new Seed {ID = "4"};
            if (list.Exists(a => seed.ID == a.ID))
            {
                WriteLog("OK");
            }
            else
            {
                WriteLog("ERROR");
            }
        }

       
        //private void CheckALL()
        //{
        //    foreach (DataGridViewRow row in GridView.Rows)
        //    {
        //        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["cbxFirend"];
        //        //cell.Value = true;
        //    }
        //}
        #endregion

        private void 工作ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ValidateUser())
            {
                tabControl1.SelectedTab = tabConsole;
                var f = new Farmer(WriteLog);
                var t = new Thread(f.DoWork);
                t.Name = "workThread";
                _pool.Add(t);
                t.Start();
            }
            else
            {
                MessageBox.Show("请先登陆");
            }           
        }

        private void 更新植物列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ValidateUser())
            {
                Store gardenStore = new Store(WriteLog);
                gardenStore.UpdateSeedList();
                MessageBox.Show("列表更新成功！");
            }
            else
            {
                MessageBox.Show("请先登陆");
            }           
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ValidateUser())
            {
                Store gardenStore = new Store(WriteLog);
                Granary gardenGranary = new Granary(WriteLog);

                tabControl1.SelectedTab = tabGardenSetting;
                gardenGridView.DataSource = gardenStore.GetSeedList();

                cbxGrass.Checked = GardenConfig.Grass;
                cbxVermin.Checked = GardenConfig.Vermin;
                cbxWater.Checked = GardenConfig.Water;
                cbxSow.Checked = GardenConfig.AutoSow;

                cbbSow.DisplayMember = "name";
                cbbSow.ValueMember = "id";
                cbbSow.DataSource = gardenStore.GetSeedList();
                cbbSow.Enabled = cbxSow.Checked;
                if (GardenConfig.SowID != -1)
                {
                    cbbSow.SelectedValue = GardenConfig.SowID.ToString();
                }

                granaryGridView.AutoGenerateColumns = false;
                granaryGridView.DataSource = gardenGranary.GetGranaryList();
            }
            else
            {
                MessageBox.Show("请先登陆");
            }
        }

        private void btnGardenSetSave_Click(object sender, EventArgs e)
        {
            if (ValidateUser())
            {
                //农田设置保存
                List<Seed> stealSeedList = new List<Seed>();
                foreach (DataGridViewRow row in gardenGridView.Rows)
                {
                    Seed seed = (Seed)row.DataBoundItem;
                    if (seed.IsSelected)
                    {
                        stealSeedList.Add(seed);
                    }
                }
                GardenConfig.StealSeeds = stealSeedList;
                GardenConfig.Water = cbxWater.Checked;
                GardenConfig.Vermin = cbxVermin.Checked;
                GardenConfig.Grass = cbxGrass.Checked;
                GardenConfig.AutoSow = cbxSow.Checked;
                GardenConfig.SowID = int.Parse(cbbSow.SelectedValue.ToString());

                MessageBox.Show("保持成功！");
            }
            else
            {
                MessageBox.Show("请先登陆");
            }           
            

        }

        private void gardenGridView_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
        {
            e.Column.ReadOnly = e.Column.Name != "gridCbxGarden";
        }

        private void cbxSow_CheckedChanged(object sender, EventArgs e)
        {
            cbbSow.Enabled = cbxSow.Checked;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (var thread in _pool)
            {
                try
                {
                    thread.Abort();
                }
                catch (Exception)
                {
                }
            }
        }

        private void 结束工作ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (ValidateUser())
            {
                foreach (var item in _pool)
                {
                    if (item.Name == "workThread" && item.IsAlive)
                    {
                        try
                        {
                            item.Abort();
                            WriteLog("工作结束");
                        }
                        catch (Exception)
                        {
                            
                        }

                    }
                }
            }
            else
            {
                MessageBox.Show("请先登陆");
            }           
            
        }

      

    }
}
